package com.xsf.pay.common.utils;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.xsf.pay.common.constants.BusinessConstants;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author huanglei
 */
@Slf4j
public class RequestUtil {
    public static String getBodyString(HttpServletRequest request) {
        //第一次获取后放入request，没拿到则从request里面取
        StringBuilder sb = new StringBuilder();
        Object attribute = request.getAttribute(BusinessConstants.REQUEST_PRRAMS);
        if(!ObjectUtil.isEmpty(attribute)){
            return attribute.toString();
        }
        try (
                InputStream inputStream = request.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            if(ObjectUtil.isEmpty(attribute)) {
                if (Tools.isTooLager(sb.toString())){
                    log.info("RequestUtil：当前查询参数过大，不打印");
                }else {
                    log.info("当前查询参数解析为：{}",sb);
                }

                request.setAttribute(BusinessConstants.REQUEST_PRRAMS, JSON.parseObject(sb.toString()));
            }
        } catch (IOException e) {
            log.error("请求参数读取异常：",e);
            if(!ObjectUtil.isEmpty(attribute)){
                return attribute.toString();
            }
        }
        return sb.toString();
    }
}
